"""
简历管理模型
"""
from django.db import models
from django.conf import settings
from django.utils import timezone
from students.models import Student


class ResumeTemplate(models.Model):
    """简历模板模型"""

    STYLE_CHOICES = [
        ('classic', '经典商务'),
        ('modern', '现代简约'),
        ('creative', '创意设计'),
        ('academic', '学术研究'),
    ]

    name = models.CharField(max_length=100, verbose_name='模板名称')
    description = models.TextField(verbose_name='模板描述')
    style_name = models.CharField(
        max_length=20,
        choices=STYLE_CHOICES,
        default='classic',
        verbose_name='样式名称'
    )
    preview_image = models.ImageField(
        upload_to='template_previews/',
        null=True,
        blank=True,
        verbose_name='预览图片'
    )
    is_premium = models.BooleanField(default=False, verbose_name='是否为精品模板')
    is_recommended = models.BooleanField(default=False, verbose_name='是否推荐')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    usage_count = models.PositiveIntegerField(default=0, verbose_name='使用次数')
    sort_order = models.PositiveIntegerField(default=0, verbose_name='排序')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'resume_template'
        verbose_name = '简历模板'
        verbose_name_plural = '简历模板'
        ordering = ['sort_order', '-is_recommended', '-usage_count']

    def __str__(self):
        return self.name

    def increment_usage(self):
        """增加使用次数"""
        self.usage_count += 1
        self.save(update_fields=['usage_count'])


class Resume(models.Model):
    """简历主表"""

    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('in_progress', '制作中'),
        ('pending_review', '待审核'),
        ('under_review', '审核中'),
        ('approved', '已通过'),
        ('rejected', '未通过'),
        ('needs_revision', '待修改'),
    ]

    TYPE_CHOICES = [
        ('uploaded', '上传简历'),
        ('generated', '在线生成'),
    ]

    student = models.ForeignKey(Student, on_delete=models.CASCADE, verbose_name='学生')
    resume_type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='generated', verbose_name='简历类型')
    uploaded_file = models.FileField(upload_to='uploaded_resumes/', blank=True, null=True, verbose_name='上传的简历文件')
    template = models.ForeignKey(ResumeTemplate, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='使用模板')
    title = models.CharField(max_length=200, default='我的简历', verbose_name='简历标题')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft', verbose_name='状态')
    current_step = models.IntegerField(default=1, verbose_name='当前步骤')
    completion_rate = models.DecimalField(max_digits=5, decimal_places=2, default=0, verbose_name='完成度')
    
    # 审核信息
    reviewer = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        limit_choices_to={'role__in': ['admin', 'teacher']},
        verbose_name='审核人'
    )
    review_date = models.DateTimeField(blank=True, null=True, verbose_name='审核时间')
    review_comments = models.TextField(blank=True, null=True, verbose_name='审核意见')
    
    # 生成的简历文件
    generated_file = models.FileField(upload_to='generated_resumes/', blank=True, null=True, verbose_name='生成的简历文件')
    generated_file_url = models.CharField(max_length=500, blank=True, null=True, verbose_name='生成文件URL')
    generated_file_name = models.CharField(max_length=255, blank=True, null=True, verbose_name='生成文件名')
    generated_file_type = models.CharField(max_length=10, blank=True, null=True, verbose_name='生成文件类型')
    generated_at = models.DateTimeField(blank=True, null=True, verbose_name='生成时间')

    # AI评估相关字段
    ai_evaluation_status = models.CharField(
        max_length=20,
        choices=[
            ('not_started', '未开始'),
            ('in_progress', '评估中'),
            ('completed', '已完成'),
            ('failed', '评估失败'),
        ],
        default='not_started',
        verbose_name='AI评估状态'
    )
    ai_evaluation_file = models.FileField(upload_to='ai_evaluations/', blank=True, null=True, verbose_name='AI评估报告文件')
    ai_evaluation_content = models.TextField(blank=True, null=True, verbose_name='AI评估内容')
    ai_evaluation_job_position = models.CharField(max_length=500, blank=True, null=True, verbose_name='评估时的岗位信息')
    ai_evaluation_at = models.DateTimeField(blank=True, null=True, verbose_name='AI评估时间')
    ai_evaluation_error = models.TextField(blank=True, null=True, verbose_name='AI评估错误信息')
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'resume_resume'
        verbose_name = '简历'
        verbose_name_plural = '简历'
        ordering = ['-updated_at']
        
    def __str__(self):
        return f"{self.student.name} - {self.title}"

    def calculate_completion_rate(self):
        """计算完成度"""
        sections = ResumeSection.objects.filter(resume=self)
        if not sections.exists():
            # 如果没有ResumeSection，使用实际数据计算
            return self.calculate_actual_completion_rate()

        completed_sections = sections.filter(is_completed=True).count()
        total_sections = sections.count()

        rate = (completed_sections / total_sections) * 100
        self.completion_rate = round(rate, 2)
        self.save(update_fields=['completion_rate'])
        return self.completion_rate

    def calculate_actual_completion_rate(self):
        """基于实际数据计算完成度"""
        total_sections = 7  # 基本信息、教育背景、技能、项目、工作经验、获奖经历、自我介绍
        completed_sections = 0

        # 检查基本信息
        try:
            basic_info = self.basicinfo
            if (basic_info.name and basic_info.phone and basic_info.email and
                basic_info.job_intention):
                completed_sections += 1
        except:
            pass

        # 检查教育背景
        if self.education_set.exists():
            completed_sections += 1

        # 检查技能
        if self.skill_set.exists():
            completed_sections += 1

        # 检查项目经验
        if self.project_set.exists():
            completed_sections += 1

        # 检查工作经验
        if self.workexperience_set.exists():
            completed_sections += 1

        # 检查获奖经历
        if self.award_set.exists():
            completed_sections += 1

        # 检查自我介绍
        try:
            self_intro = self.selfintroduction
            if self_intro and self_intro.content:
                completed_sections += 1
        except:
            pass

        completion_rate = round((completed_sections / total_sections) * 100, 2)

        # 更新数据库中的完成度
        if self.completion_rate != completion_rate:
            self.completion_rate = completion_rate
            self.save(update_fields=['completion_rate'])

        return completion_rate

    def can_submit_for_review(self):
        """检查是否可以提交审核"""
        # 只有草稿、制作中、需修改的简历可以提交审核
        if self.status not in ['draft', 'in_progress', 'needs_revision']:
            return False

        # 对于上传类型的简历，只需要检查是否有文件
        if self.resume_type == 'uploaded':
            return bool(self.uploaded_file)

        # 对于在线生成的简历，需要检查完成度
        return self.completion_rate >= 80

    def can_edit(self):
        """检查是否可以编辑"""
        # 已提交审核的简历不能编辑
        return self.status not in ['pending_review', 'under_review', 'approved']

    def submit_for_review(self, submitted_by, submission_note=None):
        """提交审核"""
        if not self.can_submit_for_review():
            raise ValueError("当前状态不允许提交审核")

        # 创建版本记录
        version_number = self.versions.count() + 1
        version = ResumeVersion.objects.create(
            resume=self,
            version_number=version_number,
            title=f"{self.title} - v{version_number}",
            status=self.status,
            completion_rate=self.completion_rate,
            submitted_at=timezone.now(),
            submission_note=submission_note
        )

        # 复制当前文件到版本
        if self.resume_type == 'uploaded' and self.uploaded_file:
            version.file_path = self.uploaded_file
            version.file_name = self.uploaded_file.name
            version.file_type = self.uploaded_file.name.split('.')[-1].lower()
            version.file_size = self.uploaded_file.size
        elif self.resume_type == 'generated' and self.generated_file:
            version.file_path = self.generated_file
            version.file_name = self.generated_file_name
            version.file_type = self.generated_file_type

        version.save()

        # 创建提交记录
        ResumeSubmission.objects.create(
            resume=self,
            version=version,
            submitted_by=submitted_by,
            submission_note=submission_note,
            previous_status=self.status
        )

        # 更新简历状态
        self.status = 'pending_review'
        self.save(update_fields=['status'])

        return version

    def get_latest_version(self):
        """获取最新版本"""
        return self.versions.first()

    def get_current_file(self):
        """获取当前文件"""
        if self.resume_type == 'uploaded' and self.uploaded_file:
            return self.uploaded_file
        elif self.resume_type == 'generated' and self.generated_file:
            return self.generated_file
        return None

    def get_structured_content(self):
        """获取结构化的简历内容"""
        try:
            content_parts = []

            # 基本信息
            if hasattr(self, 'basicinfo') and self.basicinfo:
                basic = self.basicinfo
                content_parts.append(f"""
## 个人基本信息
姓名: {basic.name or ''}
性别: {basic.gender or ''}
出生日期: {basic.birth_date or ''}
手机号: {basic.phone or ''}
邮箱: {basic.email or ''}
地址: {basic.address or ''}
求职意向: {basic.job_intention or ''}
期望薪资: {basic.expected_salary or ''}
工作地点: {basic.work_location or ''}
""")

            # 教育背景
            education_list = self.education_set.all().order_by('-start_date')
            if education_list.exists():
                content_parts.append("\n## 教育背景")
                for edu in education_list:
                    end_date = edu.end_date if edu.end_date else '至今'
                    content_parts.append(f"""
### {edu.school_name}
- 专业: {edu.major}
- 学历: {edu.degree}
- 时间: {edu.start_date} - {end_date}
- GPA: {edu.gpa or ''}
- 描述: {edu.description or ''}
""")

            # 专业技能
            skill_list = self.skill_set.all().order_by('order')
            if skill_list.exists():
                content_parts.append("\n## 专业技能")
                for skill in skill_list:
                    content_parts.append(f"""
- {skill.name} ({skill.get_level_display()})
  {skill.description or ''}
""")

            # 项目经验
            project_list = self.project_set.all().order_by('-start_date')
            if project_list.exists():
                content_parts.append("\n## 项目经验")
                for project in project_list:
                    end_date = project.end_date if project.end_date else '至今'
                    content_parts.append(f"""
### {project.name}
- 时间: {project.start_date} - {end_date}
- 公司/组织: {project.company_or_organization or ''}
- 角色: {project.role or ''}
- 项目概况: {project.overview or ''}
- 承担任务: {project.responsibilities or ''}
- 问题和总结: {project.problems_and_summary or ''}
- 使用技术: {project.technologies or ''}
- 项目成果: {project.achievements or ''}
- 项目链接: {project.url or ''}
""")

            # 工作经验
            work_list = self.workexperience_set.all().order_by('-start_date')
            if work_list.exists():
                content_parts.append("\n## 工作经验")
                for work in work_list:
                    end_date = work.end_date if work.end_date else '至今'
                    content_parts.append(f"""
### {work.company_name}
- 职位: {work.position_name or work.position or ''}
- 时间: {work.start_date} - {end_date}
- 岗位职责: {work.job_responsibilities or work.description or ''}
- 工作成果: {work.achievements or ''}
""")

            # 获奖证书
            award_list = self.award_set.all().order_by('-date_received')
            if award_list.exists():
                content_parts.append("\n## 获奖证书")
                for award in award_list:
                    content_parts.append(f"""
### {award.award_name or award.name or ''}
- 等级: {award.get_award_level_display() if hasattr(award, 'get_award_level_display') else ''}
- 颁发机构: {award.issuer or ''}
- 获得时间: {award.date_received}
- 描述: {award.award_description or award.description or ''}
""")

            # 自我介绍
            if hasattr(self, 'selfintroduction') and self.selfintroduction:
                intro = self.selfintroduction
                content_parts.append(f"""
## 自我介绍
{intro.content or ''}
""")

            return '\n'.join(content_parts)

        except Exception as e:
            # 如果出现错误，返回基本信息
            return f"简历标题: {self.title}\n学生: {self.student.name}\n简历类型: {self.get_resume_type_display()}"


# 重复的ResumeTemplate定义已删除


class ResumeGenerationRecord(models.Model):
    """简历生成记录"""

    FORMAT_CHOICES = [
        ('docx', 'Word文档'),
        ('pdf', 'PDF文档'),
    ]

    STATUS_CHOICES = [
        ('pending', '等待中'),
        ('processing', '生成中'),
        ('completed', '已完成'),
        ('failed', '失败'),
    ]

    student = models.ForeignKey(
        Student,
        on_delete=models.CASCADE,
        verbose_name='学生'
    )
    template = models.ForeignKey(
        ResumeTemplate,
        on_delete=models.CASCADE,
        verbose_name='使用的模板'
    )
    title = models.CharField(max_length=200, verbose_name='简历标题')
    format = models.CharField(
        max_length=10,
        choices=FORMAT_CHOICES,
        default='docx',
        verbose_name='生成格式'
    )
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='pending',
        verbose_name='生成状态'
    )

    # 表单数据
    form_data = models.JSONField(verbose_name='表单数据')

    # 生成的文件
    generated_file = models.FileField(
        upload_to='generated_resumes/',
        null=True,
        blank=True,
        verbose_name='生成的文件'
    )

    # 错误信息
    error_message = models.TextField(null=True, blank=True, verbose_name='错误信息')

    # 时间记录
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    started_at = models.DateTimeField(null=True, blank=True, verbose_name='开始生成时间')
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name='完成时间')

    class Meta:
        db_table = 'resume_generation_record'
        verbose_name = '简历生成记录'
        verbose_name_plural = '简历生成记录'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.student.name} - {self.title}"

    @property
    def duration(self):
        """计算生成耗时"""
        if self.started_at and self.completed_at:
            return (self.completed_at - self.started_at).total_seconds()
        return None




class ResumeSection(models.Model):
    """简历章节"""
    
    SECTION_TYPES = [
        ('basic_info', '个人基本信息'),
        ('education', '教育背景'),
        ('skills', '专业技能'),
        ('projects', '项目经验'),
        ('work_experience', '工作经验'),
        ('awards', '获奖证书'),
        ('self_introduction', '自我介绍'),
    ]
    
    resume = models.ForeignKey(Resume, on_delete=models.CASCADE, verbose_name='所属简历')
    section_type = models.CharField(max_length=20, choices=SECTION_TYPES, verbose_name='章节类型')
    title = models.CharField(max_length=100, verbose_name='章节标题')
    content = models.JSONField(default=dict, verbose_name='章节内容')
    is_completed = models.BooleanField(default=False, verbose_name='是否完成')
    order = models.IntegerField(default=0, verbose_name='排序')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'resume_section'
        verbose_name = '简历章节'
        verbose_name_plural = '简历章节'
        unique_together = ['resume', 'section_type']
        ordering = ['resume', 'order']
        
    def __str__(self):
        return f"{self.resume.student.name} - {self.title}"


class BasicInfo(models.Model):
    """个人基本信息"""
    
    resume = models.OneToOneField(Resume, on_delete=models.CASCADE, verbose_name='所属简历')
    name = models.CharField(max_length=50, verbose_name='姓名')
    gender = models.CharField(max_length=10, verbose_name='性别')
    birth_date = models.DateField(blank=True, null=True, verbose_name='出生日期')
    phone = models.CharField(max_length=20, verbose_name='手机号')
    email = models.EmailField(verbose_name='邮箱')
    address = models.CharField(max_length=200, blank=True, null=True, verbose_name='地址')
    avatar = models.ImageField(upload_to='resume_avatars/', blank=True, null=True, verbose_name='头像')
    
    # 求职意向
    job_intention = models.CharField(max_length=100, blank=True, null=True, verbose_name='求职意向')
    expected_salary = models.CharField(max_length=50, blank=True, null=True, verbose_name='期望薪资')
    work_location = models.CharField(max_length=100, blank=True, null=True, verbose_name='工作地点')
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'resume_basic_info'
        verbose_name = '个人基本信息'
        verbose_name_plural = '个人基本信息'
        
    def __str__(self):
        return f"{self.name} - 基本信息"


class Education(models.Model):
    """教育背景"""
    
    resume = models.ForeignKey(Resume, on_delete=models.CASCADE, verbose_name='所属简历')
    school_name = models.CharField(max_length=100, verbose_name='学校名称')
    major = models.CharField(max_length=100, verbose_name='专业')
    degree = models.CharField(max_length=50, verbose_name='学历')
    start_date = models.DateField(verbose_name='开始时间')
    end_date = models.DateField(blank=True, null=True, verbose_name='结束时间')
    is_current = models.BooleanField(default=False, verbose_name='是否在读')
    gpa = models.CharField(max_length=20, blank=True, null=True, verbose_name='GPA')
    description = models.TextField(blank=True, null=True, verbose_name='描述')
    order = models.IntegerField(default=0, verbose_name='排序')
    
    class Meta:
        db_table = 'resume_education'
        verbose_name = '教育背景'
        verbose_name_plural = '教育背景'
        ordering = ['resume', '-start_date']
        
    def __str__(self):
        return f"{self.resume.student.name} - {self.school_name}"


class Skill(models.Model):
    """专业技能"""
    
    SKILL_LEVELS = [
        ('beginner', '初级'),
        ('intermediate', '中级'),
        ('advanced', '高级'),
        ('expert', '专家'),
    ]
    
    resume = models.ForeignKey(Resume, on_delete=models.CASCADE, verbose_name='所属简历')
    name = models.CharField(max_length=100, verbose_name='技能名称')
    level = models.CharField(max_length=20, choices=SKILL_LEVELS, verbose_name='技能水平')
    description = models.TextField(blank=True, null=True, verbose_name='技能描述')
    order = models.IntegerField(default=0, verbose_name='排序')
    
    class Meta:
        db_table = 'resume_skill'
        verbose_name = '专业技能'
        verbose_name_plural = '专业技能'
        ordering = ['resume', 'order']
        
    def __str__(self):
        return f"{self.resume.student.name} - {self.name}"


class Project(models.Model):
    """项目经验"""

    resume = models.ForeignKey(Resume, on_delete=models.CASCADE, verbose_name='所属简历')
    name = models.CharField(max_length=200, verbose_name='项目名称')
    start_date = models.DateField(verbose_name='开始时间')
    end_date = models.DateField(blank=True, null=True, verbose_name='结束时间')
    is_current = models.BooleanField(default=False, verbose_name='是否进行中')
    company_or_organization = models.CharField(max_length=200, blank=True, null=True, verbose_name='所属公司或组织')
    overview = models.TextField(verbose_name='项目概况')
    role = models.CharField(max_length=100, verbose_name='个人角色')
    responsibilities = models.TextField(verbose_name='承担任务')
    problems_and_summary = models.TextField(blank=True, null=True, verbose_name='问题和总结')

    # 保留原有字段以兼容
    description = models.TextField(blank=True, null=True, verbose_name='项目描述')
    technologies = models.CharField(max_length=500, blank=True, null=True, verbose_name='使用技术')
    achievements = models.TextField(blank=True, null=True, verbose_name='项目成果')
    url = models.URLField(blank=True, null=True, verbose_name='项目链接')
    order = models.IntegerField(default=0, verbose_name='排序')
    
    class Meta:
        db_table = 'resume_project'
        verbose_name = '项目经验'
        verbose_name_plural = '项目经验'
        ordering = ['resume', '-start_date']
        
    def __str__(self):
        return f"{self.resume.student.name} - {self.name}"


class WorkExperience(models.Model):
    """工作经验"""

    resume = models.ForeignKey(Resume, on_delete=models.CASCADE, verbose_name='所属简历')
    company_name = models.CharField(max_length=200, verbose_name='公司名称')
    position_name = models.CharField(max_length=100, verbose_name='岗位名称')
    start_date = models.DateField(verbose_name='开始时间')
    end_date = models.DateField(blank=True, null=True, verbose_name='结束时间')
    is_current = models.BooleanField(default=False, verbose_name='是否在职')
    job_responsibilities = models.TextField(verbose_name='岗位职责')

    # 保留原有字段以兼容
    position = models.CharField(max_length=100, blank=True, null=True, verbose_name='职位')
    description = models.TextField(blank=True, null=True, verbose_name='工作描述')
    achievements = models.TextField(blank=True, null=True, verbose_name='工作成果')
    order = models.IntegerField(default=0, verbose_name='排序')
    
    class Meta:
        db_table = 'resume_work_experience'
        verbose_name = '工作经验'
        verbose_name_plural = '工作经验'
        ordering = ['resume', '-start_date']
        
    def __str__(self):
        return f"{self.resume.student.name} - {self.company_name}"


class Award(models.Model):
    """获奖证书"""

    AWARD_LEVEL_CHOICES = [
        ('school', '校级'),
        ('county', '县级'),
        ('city', '市级'),
        ('province', '省级'),
        ('national', '国家级'),
    ]

    resume = models.ForeignKey(Resume, on_delete=models.CASCADE, verbose_name='所属简历')
    award_name = models.CharField(max_length=200, verbose_name='奖项名称')
    award_level = models.CharField(max_length=20, choices=AWARD_LEVEL_CHOICES, verbose_name='奖项等级')
    certificate_photo = models.ImageField(upload_to='certificates/', blank=True, null=True, verbose_name='证书照片')
    award_description = models.TextField(blank=True, null=True, verbose_name='奖项描述')
    date_received = models.DateField(verbose_name='获得时间')

    # 保留原有字段以兼容
    name = models.CharField(max_length=200, blank=True, null=True, verbose_name='奖项名称')
    issuer = models.CharField(max_length=200, blank=True, null=True, verbose_name='颁发机构')
    description = models.TextField(blank=True, null=True, verbose_name='描述')
    certificate_file = models.FileField(upload_to='certificates/', blank=True, null=True, verbose_name='证书文件')
    order = models.IntegerField(default=0, verbose_name='排序')
    
    class Meta:
        db_table = 'resume_award'
        verbose_name = '获奖证书'
        verbose_name_plural = '获奖证书'
        ordering = ['resume', '-date_received']
        
    def __str__(self):
        return f"{self.resume.student.name} - {self.name}"


class SelfIntroduction(models.Model):
    """自我介绍"""
    
    resume = models.OneToOneField(Resume, on_delete=models.CASCADE, verbose_name='所属简历')
    content = models.TextField(verbose_name='自我介绍内容')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'resume_self_introduction'
        verbose_name = '自我介绍'
        verbose_name_plural = '自我介绍'
        
    def __str__(self):
        return f"{self.resume.student.name} - 自我介绍"


class ResumeComment(models.Model):
    """简历评论"""
    
    resume = models.ForeignKey(Resume, on_delete=models.CASCADE, verbose_name='所属简历')
    commenter = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='评论人')
    section_type = models.CharField(max_length=20, blank=True, null=True, verbose_name='章节类型')
    content = models.TextField(verbose_name='评论内容')
    is_resolved = models.BooleanField(default=False, verbose_name='是否已解决')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        db_table = 'resume_comment'
        verbose_name = '简历评论'
        verbose_name_plural = '简历评论'
        ordering = ['-created_at']
        
    def __str__(self):
        return f"{self.resume.student.name} - 评论"


class ResumeReview(models.Model):
    """简历审核记录"""

    REVIEW_STATUS_CHOICES = [
        ('approved', '通过'),
        ('rejected', '未通过'),
        ('needs_revision', '待修改'),
    ]

    resume = models.ForeignKey(Resume, on_delete=models.CASCADE, related_name='reviews', verbose_name='简历')
    reviewer = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        limit_choices_to={'role__in': ['admin', 'teacher']},
        verbose_name='审核人'
    )
    review_status = models.CharField(max_length=20, choices=REVIEW_STATUS_CHOICES, verbose_name='审核结果')
    review_comments = models.TextField(verbose_name='审核建议')
    review_date = models.DateTimeField(auto_now_add=True, verbose_name='审核时间')

    # 审核时的简历版本信息
    reviewed_file = models.FileField(upload_to='reviewed_resumes/', blank=True, null=True, verbose_name='审核时的简历文件')
    reviewed_file_name = models.CharField(max_length=255, blank=True, null=True, verbose_name='审核时的文件名')

    class Meta:
        db_table = 'resume_review'
        verbose_name = '简历审核记录'
        verbose_name_plural = '简历审核记录'
        ordering = ['-review_date']

    def __str__(self):
        return f"{self.resume.student.name} - {self.get_review_status_display()} - {self.review_date.strftime('%Y-%m-%d')}"


class ResumeVersion(models.Model):
    """简历版本历史"""

    resume = models.ForeignKey(Resume, on_delete=models.CASCADE, related_name='versions', verbose_name='简历')
    version_number = models.IntegerField(verbose_name='版本号')
    title = models.CharField(max_length=200, verbose_name='版本标题')

    # 文件信息
    file_path = models.FileField(upload_to='resume_versions/', blank=True, null=True, verbose_name='版本文件')
    file_name = models.CharField(max_length=255, blank=True, null=True, verbose_name='文件名')
    file_type = models.CharField(max_length=10, blank=True, null=True, verbose_name='文件类型')
    file_size = models.BigIntegerField(blank=True, null=True, verbose_name='文件大小')

    # 版本状态
    status = models.CharField(max_length=20, choices=Resume.STATUS_CHOICES, verbose_name='版本状态')
    completion_rate = models.DecimalField(max_digits=5, decimal_places=2, default=0, verbose_name='完成度')

    # 提交信息
    submitted_at = models.DateTimeField(blank=True, null=True, verbose_name='提交时间')
    submission_note = models.TextField(blank=True, null=True, verbose_name='提交说明')

    # 审核信息（关联到审核记录）
    review = models.OneToOneField(
        ResumeReview,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='version',
        verbose_name='审核记录'
    )

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'resume_version'
        verbose_name = '简历版本'
        verbose_name_plural = '简历版本'
        ordering = ['-version_number']
        unique_together = ['resume', 'version_number']

    def __str__(self):
        return f"{self.resume.student.name} - {self.title} - v{self.version_number}"


class ResumeSubmission(models.Model):
    """简历提交记录"""

    resume = models.ForeignKey(Resume, on_delete=models.CASCADE, related_name='submissions', verbose_name='简历')
    version = models.ForeignKey(ResumeVersion, on_delete=models.CASCADE, verbose_name='提交版本')
    submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='提交人')
    submitted_at = models.DateTimeField(auto_now_add=True, verbose_name='提交时间')
    submission_note = models.TextField(blank=True, null=True, verbose_name='提交说明')

    # 提交时的状态
    previous_status = models.CharField(max_length=20, choices=Resume.STATUS_CHOICES, verbose_name='提交前状态')

    class Meta:
        db_table = 'resume_submission'
        verbose_name = '简历提交记录'
        verbose_name_plural = '简历提交记录'
        ordering = ['-submitted_at']

    def __str__(self):
        return f"{self.resume.student.name} - 提交 v{self.version.version_number} - {self.submitted_at.strftime('%Y-%m-%d %H:%M')}"
